<template>
  <div class="app-container">
    <shipping-table
      :list="list"
      :total="total" 
      :list-loading="listLoading"
      :list-query="listQuery"
      :show-delete-filter="false"
      :show-search-input="false"
      @filter="handleFilter"
      @get-list="getList"
      @selection-change="handleSelectionChange"
      @pagination-change="handlePaginationChange"
    >
      <template #action-buttons="{ selection }">
        <el-button
          v-if="selection.length > 0"
          class="filter-item"
          type="danger"
          icon="el-icon-delete"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
        <el-button
          class="filter-item"
          type="success"
          icon="el-icon-plus"
          @click="handleCreate"
        >
          新增跨仓单
        </el-button>
      </template>
      
      <template #table-columns>
        <shipping-table-columns
          :show-id="false"
          :show-address="false"
          :show-shipping-info="false"
          :show-package-info="false"
          :show-remark="false"
          @edit="handleUpdate"
          @delete="handleDelete"
        >
          <template #custom-columns>
      <el-table-column label="物流员" prop="created_by_username" align="center" min-width="120">
        <template slot-scope="{row}">
          <span>{{ row.created_by_username || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单数" prop="order_count" align="center" min-width="100">
        <template slot-scope="{row}">
          <span>{{ row.order_count || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="箱数" prop="box_count" align="center" min-width="100">
        <template slot-scope="{row}">
          <span>{{ row.box_count || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="数量" prop="id_count" align="center" min-width="100">
        <template slot-scope="{row}">
          <span>{{ row.id_count || '-' }}</span>
        </template>
      </el-table-column>
        </template>
        </shipping-table-columns>
        </template>
    </shipping-table>

    <!-- 编辑跨仓单对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="500px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px">
        <el-form-item label="单数" prop="order_count">
          <el-input-number v-model="temp.order_count" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="箱数" prop="box_count">
          <el-input-number v-model="temp.box_count" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="数量" prop="id_count">
          <el-input-number v-model="temp.id_count" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="创建时间" prop="create_time">
          <el-date-picker
            v-model="temp.create_time"
            type="datetime"
            placeholder="请选择创建时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchCrossList, importCrossOrder, updateCrossOrder, deleteCrossOrder } from '@/api/shipping'
import ShippingTable from '@/components/ShippingTable'
import ShippingTableColumns from '@/components/ShippingTableColumns'

export default {
  name: 'CrossOrder',
  components: { ShippingTable, ShippingTableColumns },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 50
      },
      multipleSelection: [],
      dialogFormVisible: false,
      dialogStatus: '',
      temp: {
        id: undefined,
        order_count: 1,
        box_count: 1,
        id_count: 1,
        create_time: ''
      },
      rules: {
        order_count: [{ required: true, message: '单数是必填项', trigger: 'blur' }],
        box_count: [{ required: true, message: '箱数是必填项', trigger: 'blur' }],
        id_count: [{ required: true, message: '数量是必填项', trigger: 'blur' }]
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.dialogStatus === 'create' ? '新增跨仓单' : '编辑跨仓单'
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchCrossList(this.listQuery).then(response => {
        this.list = response.results?.data?.items || []
        this.total = response.count || 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$confirm('警告：删除后数据将永久丢失，无法恢复！', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
      }).then(() => {
        deleteCrossOrder(row.id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要删除的记录')
        return
      }
      this.$confirm(`警告：删除后数据将永久丢失，无法恢复！`, '批量删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
      }).then(() => {
        const deletePromises = this.multipleSelection.map(item => deleteCrossOrder(item.id))
        Promise.all(deletePromises).then(() => {
          this.$message.success('批量删除成功')
          this.getList()
        })
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          importCrossOrder(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$message.success('创建成功')
        this.getList()
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateCrossOrder(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$message.success('更新成功')
            this.getList()
          })
        }
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        order_count: 1,
        box_count: 1,
        id_count: 1,
        create_time: ''
      }
    },
    handlePaginationChange({ page, limit }) {
      this.listQuery.page = page
      this.listQuery.page_size = limit
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/shipping-common.scss';
</style> 